import { useState, useEffect } from "react";

export interface WatermarkOptions {
    content: string // 水印文本
    width?: number  // 水印宽度
    height?: number // 水印高度
    fontSize?: number // 水印字体大小
    fontColor?: string // 水印字体颜色
    zIndex?: number // 水印层级
    rotate?: number // 水印旋转角度
    gapX?: number // 水印横向间距
    gapY?: number // 水印纵向间距
}

const defaultOptions = (): Partial<WatermarkOptions> => {
    const { width, height } = document.documentElement.getBoundingClientRect()
    return {
        content: '水印文本',
        width: width,
        height: height,
        fontSize: 16,
        fontColor: 'black',
        zIndex: 9999,
        rotate: -30,
        gapX: 200,
        gapY: 100
    }

}

/**
 * gapX值越小 → 水印间距越小 → 水印更密集。
 * @param options 
 * @returns 
 */
export const useWatermark = (options: WatermarkOptions) => {
    const [watermarkOptions, setWatermarkOptions] = useState<WatermarkOptions>(options)
    const settingObj = Object.assign({}, defaultOptions(), watermarkOptions)

    const updateWatermark = (newOptions: WatermarkOptions) => {
        setWatermarkOptions((pre) => {
            return { ...pre, ...newOptions }
        }
        )
    }

    useEffect(() => {
        const cavans = document.createElement('canvas')
        const ctx = cavans.getContext('2d') as CanvasRenderingContext2D
        const { width, height, fontSize, fontColor, rotate, gapX, gapY, content } = settingObj
        cavans.width = gapX!
        cavans.height = gapY!

        // 原点移动到中心
        ctx.translate(gapX! / 2, gapY! / 2)
        // 旋转,需要将角度转换为弧度
        ctx.rotate((rotate as number) * Math.PI / 180)
        ctx.font = `${fontSize}px Arial`
        ctx.textAlign = 'center'
        ctx.fillStyle = fontColor!
        ctx.textBaseline = 'middle'
        ctx.globalAlpha = 0.15
        ctx.fillText(content, 0, 0)

        const watermark = document.createElement('div')
        watermark.style.position = 'fixed'
        watermark.id = 'watermark-id'
        watermark.style.top = '0'
        watermark.style.left = '0'
        watermark.style.width = `${width}px`
        watermark.style.height = `${height}px`
        watermark.style.pointerEvents = 'none'
        watermark.style.overflow = 'hidden'
        watermark.style.zIndex = settingObj.zIndex!.toString()
        // 将canvas作为背景图，并平铺
        watermark.style.backgroundImage = `url(${cavans.toDataURL()})`
        document.body.appendChild(watermark)

        return () => {
            // 销毁水印
            document.body.removeChild(watermark)
        }
    }, [settingObj])

    return [updateWatermark, settingObj] as const

}